<template>
  <div class="app-container">
    <el-card style="width:100%">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="queryInfo.key"
            placeholder="请输入想搜索的内容"
            clearable
            @clear="getTheseInfo"
          >
            <!-- 搜索框按钮 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getTheseInfo"
            />
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button

            class="addUser"
            @click="addVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>

      <el-table
        :data="list"
        border
        fit
        highlight-current-row
        current-row-key
        stripe
        style="width: 100%"
        :row-style="{ height: '60px' }"
      >
        <el-table-column align="center" label="序号" width="58" prop="id" />
        <el-table-column align="center" label="姓名">
          <template slot-scope="scope">
            <el-tag effect="plain" type="warning">{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="摊位名" prop="stand" />

        <el-table-column align="center" label="类型">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.type === '玩具' || scope.row.type === '小吃'"
              class="well"
            >{{ scope.row.type }}</el-tag>
            <el-tag
              v-else-if="
                scope.row.type === '数码产品' || scope.row.type === '居家用品'
              "
              class="fail"
            >{{ scope.row.type }}</el-tag>
            <el-tag v-else class="good">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="电话号码" prop="tel" />

        <el-table-column
          class-name="status-col"
          label="摊位街区"
          width="200px"
          prop="street"
        />
        <el-table-column width="100px" align="center" label="是否摆摊">
          <!-- 是否摆摊 -->
          <template slot-scope="scope">
            <i
              v-if="scope.row.status === 1"
              class="el-icon-success"
              style="color: lightgreen"
            />
            <i v-else class="el-icon-error" style="color: red" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="开始时间" prop="starttime" />
        <el-table-column align="center" label="摊位总时间" prop="alltime" />

        <el-table-column align="center" label="操作" width="321px">
          <template slot-scope="scope">
            <el-button
              class="detail"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            >详情</el-button>
            <el-button
              class="rePassword"
              icon="el-icon-setting"
              size="mini"
              @click="resetRole(scope.row)"
            >重置</el-button>
            <el-button
              class="delete"
              icon="el-icon-delete"
              size="mini"
              @click="removeInformation(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :total="total"
        :current-page="queryInfo.page"
        :page-size="10"
        layout=" prev, pager, next, jumper"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog title="详细信息" :visible.sync="editDialogVisible" width="50%">
      <span>
        <el-form
          ref="editRuleRef"
          :model="editForm"
          :rules="editRules"
          label-width="150px"
        >
          <el-form-item label="序号" prop="id">
            <el-input v-model="editForm.id" />
          </el-form-item>
          <el-form-item label="摊主名字" prop="name">
            <el-input v-model="editForm.name" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idcard">
            <el-input v-model="editForm.idcard" />
          </el-form-item>
          <el-form-item label="家庭地址" prop="address">
            <el-input v-model="editForm.address" />
          </el-form-item>
          <el-form-item label="电话号码" prop="tel">
            <el-input v-model="editForm.tel" />
          </el-form-item>
          <el-form-item label="摊位名" prop="stand">
            <el-input v-model="editForm.stand" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="editForm.description" />
          </el-form-item>
          <el-form-item label="街道(必须选一次)" prop="street">
            <el-select v-model="editForm.street" placeholder="街道">
              <el-option
                v-for="item in street"
                :key="item.id"
                :value="item.id"
                :label="item.street"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="	类型(必须选一次)" prop="type">
            <el-select v-model="editForm.type" placeholder="摊位类型">
              <el-option
                v-for="item in stand"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="摊主照片" prop="uimg">
            <el-image
              style="width: 100px; height: 100px"
              :src="url1"
              :preview-src-list="srcList1"
            />
          </el-form-item>
          <el-form-item label="摊位照片" prop="img">
            <el-image
              style="width: 100px; height: 100px"
              :src="url2"
              :preview-src-list="srcList2"
            />
          </el-form-item>
          <el-form-item label="摆摊时间" prop="date">
            <el-input v-model="editForm.date" :disabled="true" />
          </el-form-item>
          <el-form-item label="摆摊状态" prop="status">
            <el-select
              v-model="editForm.status"
              placeholder="摆摊状态"
              :disabled="true"
            >
              <el-option
                v-for="item in status"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="开始时长" prop="starttime">
            <el-input v-model="editForm.starttime" :disabled="true" />
          </el-form-item>
          <el-form-item label="结束时长" prop="endtime">
            <el-input v-model="editForm.endtime" :disabled="true" />
          </el-form-item>
          <el-form-item label="总时长" prop="alltime">
            <el-input v-model="editForm.alltime" :disabled="true" />
          </el-form-item>
          <el-form-item label="信誉分信息" prop="reputation">
            <el-cascader
              v-model="value"
              :options="options"
              :props="{ expandTrigger: 'hover' }"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item label="扣分消息">
            <el-popover placement="right" width="920" trigger="click">
              <el-table :data="message">
                <el-table-column width="180" property="date" label="日期" />
                <el-table-column width="100" property="delnum" label="扣分数" />
                <el-table-column width="100" property="type" label="扣分类型" />
                <el-table-column
                  width="300"
                  property="message"
                  label="扣分相关信息"
                />
                <el-table-column
                  width="100"
                  property="audit"
                  label="处理摊主"
                />
                <el-table-column
                  width="100"
                  property="adminName"
                  label="处理城管"
                />
              </el-table>
              <el-button slot="reference" class="delete">点击展示</el-button>
            </el-popover>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button
          class="rePassword"
          @click="editDialogVisible = false"
        >取 消</el-button>
        <el-button class="detail" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加用户"
      :visible.sync="addVisible"
      width="60%"
      @close="closeDialog"
    >
      <span>
        <el-form
          ref="addRuleRef"
          :model="addForm"
          :rules="addRules"
          label-width="100px"
        >
          <el-form-item label="摊主照片" prop="auditimg">
            <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
            >
              <el-button size="small" class="detail">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="摊位照片" prop="standimg">
            <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList2"
              list-type="picture"
            >
              <el-button size="small" class="detail">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="摊主名" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="身份证" prop="idcard">
            <el-input v-model="addForm.idcard" />
          </el-form-item>
          <el-form-item label="家庭住址" prop="address">
            <el-input v-model="addForm.address" />
          </el-form-item>
          <el-form-item label="摊主电话" prop="tel">
            <el-input v-model="addForm.tel" />
          </el-form-item>
          <el-form-item label="摊位名字" prop="stand">
            <el-input v-model="addForm.stand" />
          </el-form-item>
          <el-form-item label="街区序号" prop="street">
            <el-select v-model="addForm.street" placeholder="街道">
              <el-option
                v-for="item in street"
                :key="item.id"
                :value="item.id"
                :label="item.street"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="类型序号" prop="type">
            <el-select v-model="addForm.type" placeholder="摊位类型">
              <el-option
                v-for="item in stand"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="具体地址" prop="standdrs">
            <el-input v-model="addForm.standdrs" />
          </el-form-item>
          <el-form-item label="摊位描述" prop="description">
            <el-input v-model="addForm.description" />
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button
          class="rePassword"
          @click="addVisible = false"
        >取 消</el-button>
        <el-button class="detail" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  fetchArticle,
  addArticle,
  deleteArticle,
  resetArticle,
  getStreet,
  updateArticle
} from '@/api/information'

export default {
  name: 'InlineEditTable',
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的手机号码
        return cb()
      }
      cb(new Error('手机号码格式不正确'))
    }
    const chinaIdentityValid = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      const city = {
        11: '北京',
        12: '天津',
        13: '河北',
        14: '山西',
        15: '内蒙古',
        21: '辽宁',
        22: '吉林',
        23: '黑龙江 ',
        31: '上海',
        32: '江苏',
        33: '浙江',
        34: '安徽',
        35: '福建',
        36: '江西',
        37: '山东',
        41: '河南',
        42: '湖北 ',
        43: '湖南',
        44: '广东',
        45: '广西',
        46: '海南',
        50: '重庆',
        51: '四川',
        52: '贵州',
        53: '云南',
        54: '西藏 ',
        61: '陕西',
        62: '甘肃',
        63: '青海',
        64: '宁夏',
        65: '新疆',
        71: '台湾',
        81: '香港',
        82: '澳门',
        91: '国外'
      }
      if (
        !value ||
        !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(
          value
        )
      ) {
        callback(new Error('身份证号格式错误'))
      } else if (!city[value.substr(0, 2)]) {
        callback(new Error('身份证号格式错误'))
      } else {
        // 18位身份证需要验证最后一位校验位
        if (value.length === 18) {
          const code = value.split('')
          // ∑(ai×Wi)(mod 11)
          // 加权因子
          const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
          // 校验位
          const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
          let sum = 0
          let ai = 0
          let wi = 0
          for (let i = 0; i < 17; i++) {
            ai = code[i]
            wi = factor[i]
            sum += ai * wi
          }
          if (parity[sum % 11].toString() !== code[17]) {
            callback(new Error())
          }
        }
      }
      callback()
    }
    return {
      list: [],
      // 查询条件
      queryInfo: {
        page: 1
      },
      // 扣分消息
      message: null,
      // 总页数
      total: 2,
      // 编辑的对话框
      editDialogVisible: false,
      // 添加城管
      addVisible: false,
      // 可视框数据
      editForm: {},
      editRules: {
        name: [{ required: true, message: '请输入摊主名', trigger: 'blur' }],
        idcard: [
          { required: true, message: '请输入摊主身份证号', trigger: 'blur' },
          {
            pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
            message: '请输入正确的证件号',
            trigger: 'blur'
          },
          { validator: chinaIdentityValid, trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入摊主家庭住址', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入摊主电话号码', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ],
        stand: [{ required: true, message: '请输入摊位名字', trigger: 'blur' }],
        street: [
          { required: true, message: '请输入街道对应序号值', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入摊位类型序号值', trigger: 'blur' }
        ],
        standdrs: [
          { required: true, message: '请输入摊位具体地址', trigger: 'blur' }
        ]
      },
      status: [
        {
          id: 0,
          name: '未摆摊'
        },
        {
          id: 1,
          name: '摆摊中'
        }
      ],
      // 获取图片端口
      http: 'https://marsblue.oss-accelerate.aliyuncs.com/img/',
      url1: '',
      srcList1: [''],
      url2: '',
      srcList2: [''],
      // 添加表单验证
      addForm: {
        auditimg: '',
        standimg: '',
        name: '',
        idcard: '',
        address: '',
        tel: '',
        stand: '',
        street: '',
        type: '',
        standdrs: '',
        description: ''
      },

      addRules: {
        name: [{ required: true, message: '请输入摊主名', trigger: 'blur' }],
        idcard: [
          { required: true, message: '请输入摊主身份证号', trigger: 'blur' },
          {
            pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
            message: '请输入正确的证件号',
            trigger: 'blur'
          },
          { validator: chinaIdentityValid, trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入摊主家庭住址', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入摊主电话号码', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ],
        stand: [{ required: true, message: '请输入摊位名字', trigger: 'blur' }],
        street: [
          { required: true, message: '请输入街道对应序号值', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入摊位类型序号值', trigger: 'blur' }
        ],
        standdrs: [
          { required: true, message: '请输入摊位具体地址', trigger: 'blur' }
        ]
      },
      roleId: '',
      action1: null,
      stand: null,
      street: null,
      value: [],
      fileList: [],
      fileList2: [],
      baseUrl: null,
      options: [
        {
          value: 'anquan',
          label: '安全值',
          children: [
            {
              value: 'anquandu',
              label: 0
            }
          ]
        },
        {
          value: 'huanjing',
          label: '环境值',
          children: [
            {
              value: 'huanjingzhi',
              label: 0
            }
          ]
        },
        {
          value: 'guifanzhi',
          label: '规范',
          children: [
            {
              value: 'guifanzhi',
              label: 0
            }
          ]
        }
      ]
    }
  },
  created() {
    this.getInformation()
    this.streeType()
    // console.log(this.list);
  },
  mounted() {

  },
  methods: {
    getTheseInfo() {
      this.handleCurrentChange(1)
    },

    getInformation() {
      this.listLoading = true
      fetchList(this.queryInfo).then((response) => {
        this.list = response.data.audits
        this.total = response.data.allpage * 10
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 获取新的页数
    handleCurrentChange(newPage) {
      this.queryInfo.page = newPage
      this.getInformation()
    },
    // 展示用户信息可视化
    showEditDialog(role) {
      this.roleId = role.id

      this.listLoading = true
      fetchArticle(this.roleId).then((response) => {
        this.editForm = response.data

        this.options[0].children[0].label = this.editForm.reputation.safe
        this.options[1].children[0].label = this.editForm.reputation.envir
        this.options[2].children[0].label = this.editForm.reputation.standard
        this.url1 = this.http + this.editForm.uimg
        this.srcList1[0] = this.http + this.editForm.uimg
        this.url2 = this.http + this.editForm.img
        this.srcList2[0] = this.http + this.editForm.img

        this.message = this.editForm.reputation.message

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })

      this.editDialogVisible = true
    },
    // 新增摊主
    addUser() {
      this.$refs['addRuleRef'].validate((valid) => {
        if (valid) {
          addArticle(this.addForm).then((response) => {
            this.$alert(
              '您的账号为：' +
                response.data.account +
                ' ' +
                '密码为：' +
                response.data.password,
              '标题名称',
              {
                confirmButtonText: '确定'
              }
            )
            this.addVisible = false
            this.$notify({
              title: 'Success',
              message: '创建摊主成功',
              type: 'success',
              duration: 2000
            })
            this.getInformation()
          })
        }
      })
    },
    // 重置密码
    resetRole(role) {
      this.$confirm('重置该摊主的密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.roleId = role.id
          this.listLoading = true
          resetArticle(this.roleId).then((response) => {
            this.getInformation()
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          })

          this.$message({
            type: 'success',
            message: '重置成功,回归初始密码!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消重置'
          })
        })
    },
    // 获取街区类型
    streeType() {
      this.listLoading = true
      getStreet().then((response) => {
        this.stand = response.data.stand
        this.street = response.data.street
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // dialog关闭
    closeDialog() {
      this.$refs.addRuleRef.resetFields()
    },
    // 更新摊主信息
    updateUser() {
      this.$confirm('确定更新摊主吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          if (
            !(
              !isNaN(this.editForm.type) &&
              typeof this.editForm.type === 'number'
            ) ||
            !(
              !isNaN(this.editForm.street) &&
              typeof this.editForm.street === 'number'
            )
          ) {
            this.$alert('请务必选择一次街区和类型', '警告', {
              confirmButtonText: '确定'
            })
            return
          }

          updateArticle(this.editForm).then((response) => {
            this.getInformation()
            this.editDialogVisible = false
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          })

          this.$message({
            type: 'success',
            message: '更新成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消更新'
          })
        })
    },
    // 删除摊主
    removeInformation(role) {
      this.$confirm('此操作将永久删除该摊主, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.roleId = role.id
          this.listLoading = true
          deleteArticle(this.roleId).then((response) => {
            this.getTheseInfo()
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          })

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleChange(value) {
      console.log(value)
    },
    // 上传图片所需要的函数
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    }
  }
}
</script>

<style scoped>
.addUser {
  background-color: teal;
  color: #fff;
  border-radius: 10px;
  border: none;
}
.addUser:hover {
  background-color: rgb(2, 34, 122);
  color: #fff;
  border-radius: 10px;
  border: none;
}
.detail {
  background-color: lightseagreen;
  color: #fff;
  border-radius: 10px;
  border: none;
}
.detail:hover {
  background-color: rgb(34, 149, 194);
  color: #fff;
  border-radius: 10px;
  border: none;
}
.rePassword {
  background-color: coral;
  color: #fff;
  border-radius: 10px;
  border: none;
}
.rePassword:hover {
  background-color: rgb(245, 89, 42);
  color: #fff;
  border-radius: 10px;
  border: none;
}
.el-pagination{
  text-align: center;
}
.delete {
  background-color: tomato;
  color: #fff;
  border-radius: 10px;
  border: none;
}
.delete:hover {
  background-color: rgb(248, 46, 46);
  color: #fff;
  border-radius: 10px;
  border: none;
}
.el-table {
  margin-top: 15px;
}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.el-pagination {
  margin-top: 10px;
}
img {
  width: 30%;
}

.good{
  background-color:rgb(239, 242, 255);
  color: rgb(78, 102, 238);
  border-color: rgb(199, 235, 238) !important;
}
.well{
  background-color:rgb(239, 255, 254);
  color: rgb(112, 216, 207);
  border-color: rgb(209, 235, 229) !important;
}
.ordinary{
  background-color:rgb(255, 247, 223);
  color: rgb(253, 173, 25);
  border-color:  rgb(231, 225, 171) !important;
}
.qualified{
  background-color:rgb(239, 247, 255);
  color: rgb(112, 111, 112);
  border-color:  rgb(235, 232, 232) !important;
}
.fail{
  background-color:rgb(255, 218, 218);
  color: rgb(255, 0, 0);
  border-color:  rgb(236, 196, 196);
}
</style>
